//
//  EditCaogaoViewController.m
//  YiqiMobile
//
//  Created by henry on 13-4-26.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "EditCaogaoViewController.h"
#import "Config.h"
#import "Utility.h"
#import "AppDelegate.h"
#import "DefineAction.h"
#import "JSON.h"
#import "MBProgressHUD.h"
#import "EditBowenViewController.h"

@interface EditCaogaoViewController ()
-(void) editBowenAction:(UIButton*) sender;
-(void) caogaoTitle;
@end

@implementation EditCaogaoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.selectStatus=YES;
    float height=367;
    if (iPhone5) {
        height+=88;
    }
    self.view.frame=CGRectMake(0, 0, 320, height);

    [self initggTableView];
}

-(void) loadGonggaoDataFromServer:(NSDictionary*) param{
    self.page=1;
    self.caogaoDict=param;
     [self caogaoTitle];
    [self.ggList removeAllObjects];
    [self loadFromServer:1];
      self.isEndData=YES;
}

-(void) loadFromServer:(int) page{
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    NSMutableDictionary *param=[NSMutableDictionary dictionary];
    [param setObject:[self.caogaoDict objectForKey:@"str1"] forKey:@"id"];
    [param setObject:[NSString stringWithFormat:@"%d",page] forKey:@"type"];
    //NSLog(@"%@",[NSString stringWithFormat:@"%@/%@?g.b0=%@&g.g0=%@",[Utility  getServerUrl],GONGGAOLISTACTION,[self.caogaoDict objectForKey:@"str1"],preggId]);
    NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility  getServerUrl],GONGGAOLISTACTION];
    
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
        [[MBProgressHUD showHUDAddedTo:self.view animated:YES] setLabelText:LOADING_TITLE_DEFAULT];
    [self.request startLoadData];
}

- (void)requestFinished:(id)context{
    self.mytableView.tableFooterView.hidden=YES;
    self.mytableView.contentInset=UIEdgeInsetsMake(0, 0,0, 0);
    [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result  objectForKey:@"code"] integerValue]==0) {
            if ([[result objectForKey:@"method"] isEqualToString:GONGGAOLISTACTION]) {
                NSArray *data=[result objectForKey:@"list"];
                if (data&&(NSNull*)data!=[NSNull null]&&data.count>0) {
                    [self.ggList addObjectsFromArray:data];
                   
                    self.isEndData=NO;
                    [self.mytableView  reloadData];
                }else{
                    self.isEndData=YES;
                }
            }
            
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    self.mytableView.tableFooterView.hidden=YES;
    self.mytableView.contentInset=UIEdgeInsetsMake(0, 0,0, 0);
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:NO];
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}



-(void) initggTableView{
    CGRect rect=CGRectMake(0, 44, UISCREEN_WIDTH, self.view.frame.size.height-44);
    self.mytableView=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self.mytableView.delegate=self;
    self.mytableView.dataSource=self;
    self.mytableView.showsVerticalScrollIndicator=NO;
    self.mytableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.mytableView];
    self.ggList=[NSMutableArray array];
    [self initFootLoadingMore];
}

-(IBAction)toggleMove{
    [self.mytableView setEditing:!self.mytableView.editing animated:YES];
}

-(void) initFootLoadingMore{
    UIView *footView=[[UIView alloc] initWithFrame:CGRectMake(0,  0, self.view.frame.size.width, 30)];
    footView.tag=FOOTVIEWTAG;
    footView.backgroundColor=[UIColor  clearColor];
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc]
                                                    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.frame=CGRectMake(100, 5, 20, 20);
    [activityIndicatorView startAnimating];
    [footView addSubview:activityIndicatorView];
    UILabel *moreLabel=[[UILabel alloc] initWithFrame:CGRectMake(135, 5, 110, 20)];
    moreLabel.backgroundColor=[UIColor clearColor];
    moreLabel.textColor=[UIColor blackColor];
    moreLabel.font=[UIFont fontWithName:FONT_FAMILY size:12.0f];
    moreLabel.text=LOADING_TITLE_DEFAULT;
    [footView addSubview:moreLabel];
    self.mytableView.tableFooterView=footView;
    self.mytableView.tableFooterView.hidden=YES;
    
}

-(void) caogaoTitle{
    UIView *topBackground=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44.0f)];
    topBackground.backgroundColor=[UIColor colorWithPatternImage:[Utility imageNamed:@"cg_bg1.png"]];
    UILabel *labelTile=[Utility detailTextLabel:CGRectMake(10, 12, 200, 20) andFontSize:15.0];
    labelTile.textColor=UIColorFromRGB(0x000000);
    labelTile.text=[self.caogaoDict objectForKey:@"str2"];
    [topBackground addSubview:labelTile];
    [topBackground addSubview:[Utility customButton:self action:@selector(editBowenAction:) normalImage:@"editTitle_normal.png" lightedImage:@"editTitlehover.png" frame:CGRectMake(200,7, 111, 31) title:nil tag:0]];
    [self.view addSubview:topBackground];
}

-(void) editBowenAction:(UIButton*) sender{
    EditBowenViewController *editBowenViewController=[[EditBowenViewController alloc] initWithNibName:nil bundle:nil];
    [editBowenViewController showData:self.caogaoDict];
    [self.navigationController pushViewController:editBowenViewController animated:YES];
}





- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.ggList count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        static NSString *cellIdentity = @"EditCaogaoViewCell";
        EditCaogaoCell *cell = (EditCaogaoCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity];
        if (cell ==  nil) {
            cell = [[EditCaogaoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
              cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
    cell.delegate=self;
    cell.row=indexPath.row;
    cell.contentText.hidden=YES;
    cell.eMAsyncImageView.hidden=YES;
    cell.voiceButton.hidden=YES;
    NSDictionary *dict=[self.ggList objectAtIndex:indexPath.row];
    switch ([[dict objectForKey:@"count2"] integerValue]) {
        case 1:{//文本
            cell.contentText.hidden=NO;
            UIFont *font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
            CGSize size=[Utility getStringSize:[dict objectForKey:@"str5"] font:font withMaxSize:CGSizeMake(250, 100)];
            if (size.height>=60) {
                cell.contentText.numberOfLines=3;
                [cell setFrame:CGRectMake(0, 0, 320, 100)];
            }else{
                cell.contentText.numberOfLines=(size.height/20);
                [cell setFrame:CGRectMake(0, 0, 320, size.height+40)];
            }
            
            if (size.height>=60) {
                cell.contentText.frame=CGRectMake(42, 12, 250, 60);
            }else{
                cell.contentText.frame=CGRectMake(42, 12, 250, size.height);
            } cell.contentText.text=[dict objectForKey:@"str5"];

            break;
        }
        case 2:{//图片
            cell.eMAsyncImageView.hidden=NO;
            cell.eMAsyncImageView.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=1",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
            cell.eMAsyncImageView.frame=CGRectMake(42,12,100,100);
            cell.eMAsyncImageView.imageId=[dict objectForKey:@"str1"];
            
            cell.detailText.frame=CGRectMake(42, cell.eMAsyncImageView.frame.size.height+16, 150, 12);
            cell.statusImage.frame=CGRectMake(220, cell.contentText.frame.size.height+15, 29, 14);
            cell.detailText.text=[NSString stringWithFormat:@"阅读: %@  评论: %@",[dict objectForKey:@"count6"],[dict objectForKey:@"count5"]];
            
            [cell setFrame:CGRectMake(0, 0, 320, cell.eMAsyncImageView.frame.size.height+40)];
            break;
        }
        case 3:{//语音
            cell.voiceButton.hidden=NO;
            cell.voiceButton.frame=CGRectMake(42, 12, 38, 38);
            [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateNormal];
            [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateSelected];
            [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateHighlighted];
            cell.voiceButton.tag=indexPath.row;
            [cell.voiceButton addTarget:self action:@selector(playmp3Action:) forControlEvents:UIControlEventTouchUpInside];
            cell.detailText.frame=CGRectMake(42, cell.voiceButton.frame.size.height+21, 150, 12);
            cell.statusImage.frame=CGRectMake(220, cell.contentText.frame.size.height+20, 29, 14);
            cell.detailText.text=[NSString stringWithFormat:@"阅读: %@  评论: %@",[dict objectForKey:@"count6"],[dict objectForKey:@"count5"]];
            
            [cell setFrame:CGRectMake(0, 0, 320, cell.voiceButton.frame.size.height+40)];
            break;
        }
        case 4:{//视频
            
            break;
        }
    }

    
    //cell.selectButton.frame=CGRectMake(0, (cell.frame.size.height-27)/2,27,27);
    cell.selectButton.frame=CGRectMake(0,20,27,27);
 
        if ([[dict objectForKey:@"selected"] integerValue]==1) {
            cell.selectButton.selected=YES;
        }else{
            cell.selectButton.selected=NO;
        }
    
    if (self.selectStatus) {
        cell.selectButton.hidden=NO;
    }else{
        cell.selectButton.hidden=YES;
    }
      
        return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}

//打开编辑模式后，默认情况下每行左边会出现红的删除按钮，这个方法就是关闭这些按钮的
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView
           editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}


// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    //    需要的移动行
    NSInteger fromRow = [fromIndexPath row];
    //    获取移动某处的位置
    NSInteger toRow = [toIndexPath row];
    //    从数组中读取需要移动行的数据
    id object = [self.ggList objectAtIndex:fromRow];
    //    在数组中移动需要移动的行的数据
    [self.ggList removeObjectAtIndex:fromRow];
    //    把需要移动的单元格数据在数组中，移动到想要移动的数据前面
    [self.ggList insertObject:object atIndex:toRow];
}

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}

//---------EditCaogaoCellDelegate
-(void) editSelectActon:(UIButton*) sender andRow:(NSInteger) row{
     NSMutableDictionary *temp=[NSMutableDictionary dictionaryWithDictionary:[self.ggList objectAtIndex:row]];
    if (sender.state==UIControlStateHighlighted) {
        [temp setObject:@"1" forKey:@"selected"];
        sender.selected=YES;
    }else{
        [temp setObject:@"0" forKey:@"selected"];
        sender.selected=NO;
    }
    [self.ggList replaceObjectAtIndex:row withObject:temp];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    UIView *view=[self.view  viewWithTag:FOOTVIEWTAG];
    if (!self.isEndData&&scrollView.contentOffset.y+self.mytableView.frame.size.height-view.frame.size.height>=self.mytableView.contentSize.height) {
        self.mytableView.contentInset=UIEdgeInsetsMake(0, 0, view.frame.size.height, 0);
        self.mytableView.tableFooterView.hidden=NO;
        if (self.ggList.count>0) {
            [self loadFromServer:self.page+1];
        }
        
    }
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)playmp3Action:(UIButton*)sender{
    voiceLoading=[[UIView alloc] initWithFrame:sender.frame];
    voiceLoading.backgroundColor=[UIColor colorWithRed:249.0/255 green:249.0/255 blue:249.0/255 alpha:1.0];
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.center=CGPointMake((sender.frame.size.width-20)/2, (sender.frame.size.height-30)/2);
    [activityIndicatorView startAnimating];
    [voiceLoading addSubview:activityIndicatorView];
    [sender  addSubview:voiceLoading];
    
    NSDictionary *dict=[self.ggList objectAtIndex:[sender tag]-1];
    NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@&type=2",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
    EMAsyncFile *eMAsyncFile=[[EMAsyncFile alloc] init];
    eMAsyncFile.imageIdKey=@"id";
    eMAsyncFile.delegate=self;
    [eMAsyncFile setImageUrl:url];
    
}
#pragma -mark EMAsyncFileDelegate
-(void) fileSuccess:(NSString*)url{
    [voiceLoading removeFromSuperview];
    self.voiceRecord=[[VoiceRecord alloc] init];
    self.voiceRecord.delegate=self;
    [self.voiceRecord playMp3Click:url];
    
}
-(void) fileFail:(NSString*)error{
    [voiceLoading removeFromSuperview];
    
}


@end
